package com.xykj.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class FastJsonConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

        com.alibaba.fastjson.support.config.FastJsonConfig config = new com.alibaba.fastjson.support.config.FastJsonConfig();
        config.setCharset(StandardCharsets.UTF_8);
        config.setSerializerFeatures(
                SerializerFeature.PrettyFormat,          // 格式化输出
                SerializerFeature.WriteMapNullValue,     // 输出空字段
                SerializerFeature.WriteNullStringAsEmpty // 字符串 null 转 ""
                // 移除 DisableCircularReferenceDetect，避免潜在问题
        );
        converter.setFastJsonConfig(config);

        // 支持更多 MediaType
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.TEXT_HTML);  // 支持 HTML 内容类型
        converter.setSupportedMediaTypes(mediaTypes);

        // 插入到转换器列表首位（不清空默认转换器，避免冲突）
        converters.add(0, converter);
    }
}